package com.thekernel.youdaoyun.util;

import com.thekernel.youdaoyun.exception.impl.UserNotLoginException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @Author TheKernel
 * @Date 2019/9/14 1:42 下午
 * @Version 1.0
 * @Description 检测用户登录工具类
 */
public class UserUtils {

    /**
     * 检测用户是否已登录(工具方法)
     * @return true: 已登录 false: 未登录
     */
    private static boolean check() {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getSession();
        Enumeration<String> keys = session.getAttributeNames();
        while (keys.hasMoreElements())
            if ("userId".equals(keys.nextElement()))
                return true;
        return false;
    }

    /**
     * 检查用户是否登录, 若登录则返回对应的 id, 否则抛出未登录异常
     * @return 用户 id
     * @throws UserNotLoginException 未登录异常
     */
    public static long checkReturnUserId() throws UserNotLoginException {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest()
                .getSession();
        boolean flag = UserUtils.check();
        if (!flag)
            throw new UserNotLoginException();
        else
            return (long) session.getAttribute("userId");
    }

}
